import { useMessage } from '@hooks/useAppMessage'
import { useAxios } from '@hooks/useAxios'
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
import { API_PRODUCT_URL } from './baseApi'

export const useProductQuery = (params) => {
  const { http } = useAxios()
  return useQuery({
    queryKey: ['product.list', params],
    queryFn: async () => {
      return await http.get(API_PRODUCT_URL, { params })
    },
  })
}

export const useProductDetailQuery = (id) => {
  const { http } = useAxios()
  return useQuery({
    queryKey: ['product.detail', id],
    queryFn: async () => {
      const response = await http.get(`${API_PRODUCT_URL}/${id}`)
      return response.data
    },
    // staleTime: 1000 * 60 * 5, // 5 minutes
    enabled: !!id,
  })
}

export const useProductUpdateMutation = (cb) => {
  const message = useMessage()
  const { http } = useAxios()
  return useMutation({
    mutationFn: async (data) => {
      const response = await http.put(`${API_PRODUCT_URL}/${data.id}`, data)
      return response.data
    },
    onSuccess: (data) => {
      console.log('product updated', data)
      message.success('更新成功').then(cb?.())
    },
  })
}

export const useProductDeleteMutation = () => {
  const { http } = useAxios()
  const message = useMessage()
  const queryClient = useQueryClient()
  return useMutation({
    mutationFn: async (ids) => await http.delete(`${API_PRODUCT_URL}`, { data: { ids } }),
    onSuccess: () => {
      queryClient.invalidateQueries(['product.list'])
      message.success('删除成功')
    },
  })
}

export const useProductCreateMutation = (onSuccess) => {
  const { http } = useAxios()
  const message = useMessage()
  const queryClient = useQueryClient()
  return useMutation({
    mutationFn: async (data) => await http.post(API_PRODUCT_URL, data),
    onSuccess: () => {
      queryClient.invalidateQueries(['product.list'])
      message.success('保存成功').then(onSuccess)
    },
  })
}
